package com.recycle.filter;

import cn.hutool.core.util.StrUtil;
import com.recycle.common.ResPonseCode;
import com.recycle.common.ServerResponse;
import com.recycle.util.JsonUtil;
import com.recycle.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 拦截器：Spring框架特有的，常用于登录校验，权限校验，请求日志打印
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(UserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOG.info("UserInterceptor开始");
        response.reset();
        response.setCharacterEncoding("UTF-8");//geelynote 这里要设置编码，否则会乱码
        response.setContentType("application/json;charset=UTF-8");//geelynote 这里要设置返回值的类型，因为全部是json接口。
        //获取header的token参数
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
         boolean flag =    JwtUtil.validate(token);
         if(!flag){
             PrintWriter printWriter =  response.getWriter();
             printWriter.print(JsonUtil.obj2String( ServerResponse.ErrorModelCodeMessage(ResPonseCode.NEED_LOGIN.getCode(), "请登录")));
             printWriter.flush();
             printWriter.close();
             return false;
         }
        }else{
            PrintWriter printWriter =  response.getWriter();

            printWriter.print(JsonUtil.obj2String( ServerResponse.ErrorModelCodeMessage(ResPonseCode.ILLEGAL_ARGUMENT.getCode(), "token不存在")));
            printWriter.flush();
            printWriter.close();
            return false;
        }
        LOG.info("MemberInterceptor结束");
        return true;
    }

}
